<template>
  <div class="mainContainer">
    <div style="display:flex;justify-content:space-between;align-items:flex-start">
      <div style="max-height:100vh;overflow-y:auto;flex-grow:1" class="componentCanvas" @click.stop="noAct">
        <el-row type="flex" justify="space-between">
          <div>
            <canvas id="canvas" width="300" height="300" style="border:1px solid #efefef"></canvas>
          </div>
          <div style="width:300px;margin-right:20px;">
            <el-upload :before-upload="onUpload">
              <el-button @click="addImg">添加图片</el-button>
            </el-upload>
            <el-button @click="addText">添加文字</el-button>
            <el-button @click="addBg">添加背景</el-button>
            <el-button @click="onOut">导出</el-button>
            <el-button @click="onOutElement">导出Element</el-button>
            <el-button @click="noAct">放弃选中</el-button>
            <el-button @click="createGroup">新建一个组</el-button>
            <el-button @click="resetZoom">重置缩放</el-button>
            <el-button @click="test">测试层级</el-button>
            <el-upload :before-upload="onIn">
              <el-button>导入</el-button>
            </el-upload>
            <div>
              <el-form :label-width="50">
                <el-form-item label="名称">
                  <el-input v-model="tab.label"></el-input>
                </el-form-item>
                <el-form-item label="宽度">
                  <el-input v-model="stage.width"></el-input>
                </el-form-item>
                <el-form-item label="高度">
                  <el-input v-model="stage.height"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-row type="flex" justify="end" style="width:100%">
                    <el-button @click="onSet">设置</el-button>
                  </el-row>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-row>
      </div>
      <div class="componentPanel">
        <div class="cp-title">
          组件列表
        </div>
        <elem-list v-if="isLoad" :element="ec"></elem-list>
      </div>
    </div>
    <div id="main"></div>
  </div>
</template>
<script>
import { default as Element, zrender, ElementUI } from '../../../../../daydayup2021/js/element2/dist/Element2Wx-1.0.1.esm.js'
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import { fabric } from 'fabric'
import { ref, markRaw } from 'vue'
import CanvasElement from '../element/Element.js'
import { createCanvasComponent, FlowGroup } from '../element/component.js'
import testJson from '../../../json/ouput_bk.json'
import ElemList from '../element/ElemList.vue'
export default {
  props: ['tab'],
  components: {
    Plus,
    ElemList
  },
  data() {
    return {
      a: 1,
      b: 2,
      stage: {
        width: 300,
        height: 300
      },
      current: null,
      ec: null,
      isLoad: false
    }
  },
  methods: {
    resetZoom() {
      this.ec.resetZoom()
    },
    createGroup() {
      this.ec.createGroup()
    },
    onChangeGroup(e) {
      console.log(this.current)
      this.ec.addElemToGroup(this.current, e)
    },
    onSet() {
      this.ec.setWidth(this.stage.width)
      this.ec.setHeight(this.stage.height)
    },
    noAct(e) {
      console.log(e.target.nodeName)
      if (e.target.nodeName != 'CANVAS') {
        this.ec.noAct()
      }
    },
    onOut() {
      this.ec.output()
    },
    onOutElement() {
      let json = this.ec.outputElement2()
      let main = zrender.init(document.getElementById('main'), {
        width: json.w,
        height: json.h
      })
      console.log(json)
      let element = new Element(json)
      ElementUI.render({
        main,
        element
      })
    },
    onIn(file) {
      this.ec.inputByFile(file).then((json) => {
        this.stage = {
          width: json.width,
          height: json.height
        }
      })
      return false
    },
    onUpload(file) {
      this.ec.createImgByFile(file, this.stage)
      return false
    },
    addImg() {},
    changeImg(file) {
      let fr = new FileReader()
      fr.readAsDataURL(file)
      fr.onload = (e) => {
        let result = e.target.result
        this.ec.scaleImgFit(result, this.stage).then((res) => {
          this.current.update({
            src: result,
            ...res
          })
        })
      }
      return false
    },
    addBg() {
      var rect = new fabric.Rect({
        width: 100,
        height: 100,
        fill: '#efefef'
      })
      this.ec.add(rect, {
        config: {
          type: 'bg',
          selectable: 1
        }
      })
    },
    addText() {
      var text = new fabric.Text('这里输入文字', {
        fontSize: 16,
        lineHeight: 1
      })
      this.ec.add(text)
    },
    onChangeText(e) {
      this.current.update({
        text: e
      })
    },
    onChangeFont(e) {
      this.current.update({
        fontSize: e
      })
    },
    save() {
      //修改了
    },
    test() {
      console.log(this.canvas.toJSON())
      let obj = this.canvas.toObject(['guid'])
      let levelArr = {}
      const deepLevel = (objects, parentLevel = []) => {
        objects.forEach((res, i) => {
          let pl = Object.assign([], parentLevel)
          pl.push(i)
          if (res.objects && res.objects.length) {
            deepLevel(res.objects, pl)
          }
          let z = 0
          for (var p = 0; p < pl.length; p++) {
            z = z + pl[p] * Math.pow(0.01, p)
          }
          levelArr[res.guid] = {
            z: z,
            level: pl
          }
        })
      }
      deepLevel(obj.objects)
    }
  },
  watch: {},
  mounted() {
    let dom = this.$el.querySelector('#canvas')
    const canvas = new fabric.Canvas(dom, {
      selection: false,
      width: this.stage.width,
      height: this.stage.height
    })
    console.log(canvas)
    let ec = createCanvasComponent({
      component: canvas,
      onSelection: (target) => {
        if (target) {
          let guid = target.guid
          let elem = $('#' + guid)
          if (elem.length) {
            elem
              .addClass('on')
              .siblings()
              .removeClass('on')
            let off = elem.offset()
            let st = $('.componentPanel').scrollTop()
            $('.componentPanel').animate(
              {
                scrollTop: off.top + st
              },
              0
            )
          }
        } else {
          $('.componentPanel .cp-item').removeClass('on')
        }
        //this.current = target
      },
      onSave: (target) => {},
      context: this
    })

    var text = new CanvasElement({
      component: new fabric.Text('这这这\n这里有很', {
        fontSize: 30,
        lineHeight: 1,
        top: 50
      }),
      canvas
    })

    let img = new Image()
    /*img.src = 'https://hangjiayun.oss-cn-shanghai.aliyuncs.com/allxcx/credit/images/act-ava.png'*/
    let fg = new FlowGroup({
      canvas
    })
    img.src = require('../element/act-ava.png')
    img.onload = () => {
      var image = new CanvasElement({
        component: new fabric.Image(img, {
          left: 0,
          top: 0
        }),
        canvas
      })
      /*ec.add(image)*/
      fg.add(image)
      var text2 = new CanvasElement({
        component: new fabric.Text('这这这\n这里有很', {
          fontSize: 30,
          lineHeight: 1,
          top: 130
        }),
        canvas
      })

      fg.add(text2)
      console.log(fg)
    }
    this.ec = markRaw(ec)
    this.isLoad = true
    /*ec.add(text)*/
    fg.add(text)
    ec.addElem(fg)
  }
}
</script>
<style type="text/css" lang="scss">
body {
  padding: 0;
  margin: 0;
}
.componentCanvas {
  &::-webkit-scrollbar {
    width: 4px;
    height: 1px;
  }

  &::-webkit-scrollbar-thumb {
    background: #aaa;
  }

  &::-webkit-scrollbar-track {
    background: #fff;
  }
}
.componentPanel {
  max-height: 100vh;
  overflow-y: auto;
  box-sizing: border-box;
  border: 1px solid #efefef;
  padding: 0px;
  .cp {
    &-title {
      padding: 10px;
    }
    &-group {
    }
    &-item {
      border-bottom: 1px solid #efefef;
      padding: 10px 5px 5px 5px;
      &:last-child {
        border-bottom: 0;
      }
      transition: all 0.5s ease;
      &.on {
        background: #efefef;
      }
    }
    &-group {
    }
    &-group-childs {
      padding: 0px 10px;
    }
  }
  &::-webkit-scrollbar {
    width: 4px;
    height: 1px;
  }

  &::-webkit-scrollbar-thumb {
    background: #aaa;
  }

  &::-webkit-scrollbar-track {
    background: #fff;
  }
}
.box {
  width: 100px;
  height: 100px;
  border: 1px solid #000;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
